import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Row, Col, Input } from 'antd';
import { InputC, InputNumberC, SingleDateC, TradingMarketC } from '../../../../comps';
import moment from 'moment';
import style from './myStyle.less';
import FormItemLayout from './formItemLayout';
@Form.create()
class BuyBackOrderC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
  };
  constructor() {
    super();
    this.state = {
      buyBackMoney: undefined, // 回购金额
      buyBackRate: undefined, // 回购利率
      occupationDays: undefined, // 实际占款天数
    };
  }
  componentDidMount() {
    this.props.onRef(this);
  }
  // 回购天数改便回填回购代码
  changeBuyBackDay = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
      dispatch,
    } = this.props;
    const { buyBackMoney, buyBackRate } = this.state;
    const pad = (num, n) => {
      let len = num.toString().length;
      while (len < n) {
        num = '0' + num;
        len++;
      }
      return num;
    };
    const str = (e) => {
      let test = '';
      if (0 < e && e <= 14) {
        test = `R${pad(e, 3)}`;
      } else if (14 < e && e <= 21) {
        test = 'R021';
      } else if (21 < e && e <= 30) {
        test = 'R1M';
      } else if (30 < e && e <= 90) {
        test = 'R3M';
      } else if (90 < e && e <= 180) {
        test = 'R6M';
      } else if (180 < e && e <= 270) {
        test = 'R9M';
      } else if (270 < e && e <= 365) {
        test = 'R1Y';
      }
      return test;
    };
    //生成回购代码，计算到期结算金额和到期结算日，条件不足时，到期结算金额和到期结算日置空
    if (e && e !== 0 && typeof e == 'number') {
      setFieldsValue({
        buybackCode: str(e), // 根据回购天数回填回购代码
      });
      dispatch({
        type: 'interBankBasicInfoM/getBackInfo',
        payload: {
          repurchaseDays: e,
          firstSettlemenDate: getFieldValue('firstSettlementDate').format('YYYY-MM-DD'),
          type: 'transfer',
        },
        callback: (res) => {
          this.setState({
            occupationDays: res.occupationDays, // 实际占款天数
          });
          setFieldsValue({
            settlementDate: moment(res.settlementDate),
          });
          if (buyBackMoney !== undefined && buyBackRate !== undefined) {
            //到期结算金额 = 回购金额 + 回购金额*（回购利率*0.01*实际占款天数/365）
            const num = buyBackMoney * (parseFloat(buyBackRate * 0.01) * parseFloat(res.occupationDays / 365)) + buyBackMoney;
            setFieldsValue({
              expireAmount: num,
            });
          } else {
            setFieldsValue({
              expireAmount: undefined,
            });
          }
        },
      });
    } else {
      setFieldsValue({
        // 回购天数清空，清空回购代码，占款天数，到期结算日期
        settlementDate: undefined,
        buybackCode: undefined,
        expireAmount: undefined,
      });
    }
  };
  // 设置回购利率
  setBuyBackRate = () => {
    const { buyBackMoney, buyBackRate, occupationDays } = this.state;
    const {
      form: { setFieldsValue },
    } = this.props;
    // 回购金额不为空并且回购利率不为空时计算到期结算金额
    if (buyBackMoney !== undefined && buyBackRate !== undefined && occupationDays !== undefined) {
      const num = buyBackMoney * (parseFloat(buyBackRate * 0.01) * parseFloat(occupationDays / 365)) + buyBackMoney;
      setFieldsValue({
        expireAmount: num,
      });
    } else {
      setFieldsValue({
        expireAmount: undefined,
      });
    }
  };
  formContent = () => {
    return (
      <>
        <Form>
          <Row>
            <Col span={24}>
              <TradingMarketC // 交易市场
                title='交易市场'
                form={this.props.form}
                dataIndex='exchangecode'
                marketType={['yhj']}
                initialValue={'113'}
                rules={[{ required: true, message: '请选择交易市场!' }]}
                formItemLayout={FormItemLayout}
                disabled={true}
              />
            </Col>
            <Col span={24}>
              <InputNumberC
                title='回购天数'
                dataIndex='repurchaseDays'
                placeholder='请输入'
                min={1}
                max={365}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                onChange={this.changeBuyBackDay}
                rules={[{ required: true, message: `请输入回购天数` }]}
                unit='天'
              />
            </Col>
            <Col span={24}>
              <InputC title='回购代码' dataIndex='buybackCode' form={this.props.form} disabled={true} formItemLayout={FormItemLayout} />
            </Col>
            <Col span={24}>
              <InputNumberC
                title='回购金额'
                dataIndex='repurchaseAmount'
                placeholder='请输入'
                precision={2}
                min={0.01}
                max={999999999999}
                splitStyle={true}
                onChange={(e) => {
                  this.setState(
                    {
                      buyBackMoney: e,
                    },
                    () => this.setBuyBackRate(),
                  );
                }}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                rules={[
                  { required: true, message: `请输入回购金额` },
                  { pattern: /^[1-9]\d*0000$/, message: '请输入10000的倍数' },
                ]}
              />
            </Col>
            <Col span={24}>
              <InputNumberC
                title='回购利率'
                dataIndex='repoRate'
                placeholder='请输入'
                precision={4}
                min={0.0001}
                max={100}
                splitStyle={true}
                onChange={(e) => {
                  this.setState(
                    {
                      buyBackRate: e,
                    },
                    () => this.setBuyBackRate(),
                  );
                }}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                rules={[{ required: true, message: `请输入回购利率` }]}
                unit='%'
              />
            </Col>
            <Col span={24}>
              <InputNumberC
                title='到期结算金额'
                dataIndex='expireAmount'
                placeholder='请输入'
                precision={2}
                splitStyle={true}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                rules={[{ required: true, message: `请输入到期结算金额` }]}
                disabled={true}
                unit='元'
              />
            </Col>
            <Col span={24}>
              <SingleDateC form={this.props.form} title='首期结算日期' dataIndex='firstSettlementDate' initialValue={moment()} disabled={true} formItemLayout={FormItemLayout} />
            </Col>
            <Col span={24}>
              <SingleDateC form={this.props.form} title='到期结算日期' dataIndex='settlementDate' disabled={true} formItemLayout={FormItemLayout} />
            </Col>
          </Row>
        </Form>
      </>
    );
  };

  // 获取校验并获取表单的值
  getInfo = () => {
    const {
      form: { validateFields },
    } = this.props;
    let query = {};
    validateFields((err, fieldsValue) => {
      if (!err) {
        query = fieldsValue;
        query.firstSettlementDate = query.firstSettlementDate.format('YYYY-MM-DD');
        query.settlementDate = query.settlementDate.format('YYYY-MM-DD');
      }
    });
    if (JSON.stringify(query) == '{}') {
      query = undefined;
    } else {
      if (query.raisedMoney < 0 || query.monery < 0 || query.buyBackRate < 0) {
        message.warning('回购天数、回购金额、回购利率不得小于0');
        query = undefined;
      }
    }
    return query;
  };

  render() {
    return <div>{this.formContent()}</div>;
  }
}

export default connect(({ interBankBasicInfoM, isAccountConfiguredM }) => ({
  interBankBasicInfoM,
  isAccountConfiguredM,
}))(BuyBackOrderC);
